package com.example.spring.test;

import java.util.concurrent.locks.ReentrantLock;

public class FairLock {


    public static void main(String[] args) {
        //true 表示ReentrantLock的公平锁
        ReentrantLock lock = new ReentrantLock(false);
        for (int i = 0; i < 10; i++) {
            new Thread(new FairDemo(lock)).start();
        }
    }

    static class FairDemo implements Runnable {
        ReentrantLock lock;

        public FairDemo(ReentrantLock lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + "启动");
                lock.lock();
                System.out.println(Thread.currentThread().getName() + "获得了锁");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }


}
